package com.sy.service.permissions.impl;

import com.sy.bean.permissions.role.Role;
import com.sy.common.crud.BaseServiceImpl;
import com.sy.common.exception.BusinessException;
import com.sy.common.utils.DateUtils;
import com.sy.mapper.permissions.RoleMapper;
import com.sy.service.permissions.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl extends BaseServiceImpl<Role, RoleMapper> implements RoleService {
    @Autowired
    RoleMapper roleMapper;

    @Transactional
    @Override
    public int save(Role entity) {
        entity.setStatus(1);
        entity.setCode(DateUtils.setCode(""));
        int rs = roleMapper.save(entity);
        if (entity.getMenu() == null)
            throw new BusinessException("角色权限不可为空");
        if (rs < 1)
            throw new BusinessException("新增失败");
        rs = roleMapper.batchSave(entity.getId(), entity.getMenu());
        if (rs < 1)
            throw new BusinessException("新增失败");
        return 1;
    }

    @Transactional
    @Override
    public int update(Role entity) {
        int rs = roleMapper.update(entity);
        if (rs < 1)
            throw new BusinessException("修改失败");
        //先删除该角色的所有权限
        rs = roleMapper.deleteRM(entity.getId());
        if (rs < 1)
            throw new BusinessException("修改失败");
        //再添加修改后的权限
        rs = roleMapper.batchSave(entity.getId(), entity.getMenu());
        if (rs < 1)
            throw new BusinessException("修改失败");
        return super.update(entity);
    }

    @Override
    public int editStatus(Role role) {
        return roleMapper.editStatus(role);
    }

    @Override
    public List<Integer> queryMenuId(int roleId) {
        return roleMapper.queryMenuId(roleId);
    }
}
